package com.mai.realtime.app.dws;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mai.realtime.app.BaseAppV1;
import com.mai.realtime.bean.ExamScoreBean;
import com.mai.realtime.common.Constant;
import com.mai.realtime.util.AtguiguUtil;
import com.mai.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * com.mai.realtime.app.dws.Dws_ExamScoreCountWindow
 * 考试分数段指标统计
 */
public class Dws_ExamScoreCountWindow extends BaseAppV1 {
    public static void main(String[] args) {
        new Dws_ExamScoreCountWindow().init(
                4012,
                1,
                "Dws_ExamScoreCountWindow",
                Constant.TOPIC_DWD_COURSE_TEST_EXAM
        );
    }

    @Override
    protected void handle(StreamExecutionEnvironment env, DataStreamSource<String> stream) {
        // 1:封装
        SingleOutputStreamOperator<ExamScoreBean> examScoreBeanStream = ExamScoreToPojo(stream);

        // 2:开窗聚合
        SingleOutputStreamOperator<ExamScoreBean> examScoreWindow = ExamScoewAggWindow(examScoreBeanStream);

        // 4:写出
        examScoreWindow
                .map(bean -> JSON.toJSONString(bean))
                .print();
        //.addSink(FlinkSinkUtil.getDorisSink("gmall.dws_exam_score_count_window"));

    }

    private SingleOutputStreamOperator<ExamScoreBean> ExamScoewAggWindow(SingleOutputStreamOperator<ExamScoreBean> examScoreBeanStream) {
        return examScoreBeanStream
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<ExamScoreBean>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((bean, ts) -> bean.getTs() * 1000)
                )
                .keyBy(json -> json.getPaperId())
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(10)))
                .reduce(new ReduceFunction<ExamScoreBean>() {
                            @Override
                            public ExamScoreBean reduce(ExamScoreBean bean1,
                                                        ExamScoreBean bean2) throws Exception {
                                bean1.setScore90(bean1.getScore90() + bean2.getScore90());
                                bean1.setScore80(bean1.getScore80() + bean2.getScore80());
                                bean1.setScore70(bean1.getScore70() + bean2.getScore70());
                                bean1.setScore60(bean1.getScore60() + bean2.getScore60());
                                bean1.setScore60(bean1.getScore60() + bean2.getScore60());

                                return bean1;
                            }
                        },

                        new ProcessAllWindowFunction<ExamScoreBean, ExamScoreBean, TimeWindow>() {

                            @Override
                            public void process(Context ctx,
                                                Iterable<ExamScoreBean> elements,
                                                Collector<ExamScoreBean> out) throws Exception {
                                ExamScoreBean bean = elements.iterator().next();

                                bean.setStt(AtguiguUtil.toDateTime(ctx.window().getStart()));
                                bean.setEdt(AtguiguUtil.toDateTime(ctx.window().getEnd()));
                                bean.setCurDate(AtguiguUtil.toDate(ctx.window().getStart()));

                                out.collect(bean);

                            }
                        }
                );
    }

    private SingleOutputStreamOperator<ExamScoreBean> ExamScoreToPojo(DataStreamSource<String> stream) {
        return stream
                .map(json -> {
                    JSONObject obj = JSON.parseObject(json);
                    String paper_id = obj.getString("paper_id");

                    Long ts = obj.getLong("ts");
                    Double score = obj.getDouble("score");

                    ExamScoreBean examScoreBean = new ExamScoreBean("", "",
                            "", paper_id,
                            0L, 0L, 0L, 0L, 0L,
                            ts);

                    if (score >= 90) {
                        examScoreBean.setScore90(1L);
                    } else if (score >= 80) {
                        examScoreBean.setScore90(1L);

                    } else if (score >= 70) {
                        examScoreBean.setScore90(1L);

                    } else if (score >= 60) {
                        examScoreBean.setScore90(1L);

                    } else {
                        examScoreBean.setScore90(1L);
                    }


                    return examScoreBean;

                });
    }
}
